package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.louwowo.cache.key.RedisKeys;
import cn.wolfcode.louwowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.louwowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.louwowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.louwowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

@Controller
@RequestMapping("travel")
public class TravelController {
    @Value("${file.path}")
    private String filePath;

    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisRedisService travelStatisRedisService;
    @Reference
    private IStrategyStatisRedisService strategyStatisRedisService;

    @RequestMapping("")
    public String list(Model model,@ModelAttribute("qo") TravelQuery qo){
        List<Travel> list = travelService.query(qo).getList();
        for (Travel travel : list) {
            TravelStatisVO travelVO = travelStatisRedisService.getStatisVo(travel.getId());
            travel.setThumbsupnum(travelVO.getThumbsupnum());
        }
        model.addAttribute("pageInfo", new PageInfo<>(list));
        model.addAttribute("tcs",travelCommentService.getCreateTimeTop10());
        List<StrategyStatisVO> hotStrategys = new ArrayList<>();
        List<StrategyStatisVO> vos = strategyStatisRedisService.getVoByZsetKey(RedisKeys.STRATEGY_STATIS_CHINA_HOT_SORT.getPrefit(),
                0, -1);
        for (StrategyStatisVO vo : vos) {
            if((!vo.isIsabroad()) && hotStrategys.size() < 10){
                hotStrategys.add(vo);
            }
        }
        model.addAttribute("hotStrategys",hotStrategys);
        return "travel/list";
    }

    @RequestMapping("detail")
    public String detail(Model model, Long id,@UserParam UserInfo userInfo){
        Travel travel = travelService.get(id);
        Long destId = travel.getDest().getId();
        model.addAttribute("detail", travel);
        List<Destination> toasts = destinationService.getToasts(destId);
        toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts",toasts);
        model.addAttribute("sds",strategyDetailService.getViewnumTop3DetailsByDestId(destId));
        model.addAttribute("ts",travelService.getViewnumTop3TravelsByDestId(destId));
        //评论的集合
        model.addAttribute("list",travelCommentService.listAll());
        travelStatisRedisService.viewNumIncrease(id,1);
        TravelStatisVO statisVo = travelStatisRedisService.getStatisVo(id);
        model.addAttribute("vo", travelStatisRedisService.getStatisVo(id));
        if(userInfo != null){
            //用户登陆时，判断该攻略是否被当前用户收藏，用于收藏样式的回显
            model.addAttribute("isFavor",travelStatisRedisService.isFavor(userInfo.getId(),id));
        }
        return "travel/detail";
    }

    @RequireLogin
    @RequestMapping("input")
    public String input(Model model,Long id){
        if(id != null){
            Travel travel = travelService.get(id);
            model.addAttribute("tv", travel);
        }
        model.addAttribute("dests",destinationService.getDestByDeep(3));
        return "travel/input";
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);
        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    @RequireLogin
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public AjaxResult saveOrUpdate(Travel travel, @UserParam UserInfo userInfo){
        //author，作者
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        return new AjaxResult().getData(id);
    }

    @RequireLogin
    @RequestMapping("commentAdd")
    public String commentAdd(Model model, TravelComment travelComment,
                             @UserParam UserInfo userInfo,
                             int floor){
        //补充用户信息
        travelComment.setUserId(userInfo.getId());
        travelComment.setUsername(userInfo.getNickname());
        travelComment.setCity(userInfo.getCity());
        travelComment.setLevel(userInfo.getLevel());
        travelComment.setHeadUrl(userInfo.getHeadImgUrl());
        TravelComment comment = travelCommentService.saveOrUpdate(travelComment);
        model.addAttribute("floor", floor + 1);
        model.addAttribute("c",comment);
        return "travel/commentTpl";
    }

    @RequestMapping("travelThumbup")
    @ResponseBody
    public AjaxResult travelThumbup(Long tid,@UserParam UserInfo userInfo){
        //先判断是否登陆
        if(userInfo == null){
            return AjaxResult.UNLOGIN();
        }
        boolean b = travelStatisRedisService.thumbup(tid, userInfo.getId());
        //true表示是已顶过了，false表示今天还没顶
        return new AjaxResult(!b,"").getData(travelStatisRedisService.getStatisVo(tid));
    }

    @RequestMapping("favor")
    @ResponseBody
    public AjaxResult favor(Long tid,@UserParam UserInfo userInfo){
        //先判断是否登陆
        if(userInfo == null){
            return AjaxResult.UNLOGIN();
        }
        boolean b = travelStatisRedisService.favor(userInfo.getId(),tid);
        //true表示是收藏操作，false表示取消收藏
        return new AjaxResult(b,"").getData(travelStatisRedisService.getStatisVo(tid));
    }

    @RequestMapping("shareAdd")
    @ResponseBody
    public AjaxResult shareAdd(Long tid){
        travelStatisRedisService.shareNumIncrease(tid, 1);
        return new AjaxResult().getData(travelStatisRedisService.getStatisVo(tid));
    }
}
